<template>
  <div class="services">
    <header class="mb-8">
      <h1 class="glow-text">服务管理</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <div class="relative">
          <input
            type="text"
            class="input pr-10"
            placeholder="搜索服务..."
            v-model="searchQuery"
          />
          <svg class="w-5 h-5 absolute right-3 top-2.5 text-light-dark" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
          </svg>
        </div>

        <div class="ml-4">
          <select class="input bg-dark-darker" v-model="statusFilter">
            <option value="all">所有状态</option>
            <option value="active">活跃</option>
            <option value="inactive">非活跃</option>
            <option value="error">错误</option>
          </select>
        </div>
      </div>

      <button class="btn btn-primary">
        <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
        </svg>
        刷新
      </button>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <div
        v-for="service in filteredServices"
        :key="service.id"
        class="tech-card hover:border-primary transition-all duration-300"
        @click="selectService(service)"
      >
        <div class="flex justify-between items-start mb-4">
          <h3 class="text-xl font-medium">{{ service.name }}</h3>
          <span
            :class="{
              'badge badge-blue': service.status === 'active',
              'badge badge-yellow': service.status === 'inactive',
              'badge badge-pink': service.status === 'error'
            }"
          >
            {{ service.status === 'active' ? '活跃' : service.status === 'inactive' ? '非活跃' : '错误' }}
          </span>
        </div>

        <div class="text-sm text-light-dark mb-4">
          <div class="mb-1">命名空间: {{ service.namespace }}</div>
          <div class="mb-1">IP: {{ service.ip }}</div>
          <div>端口: {{ service.port }}</div>
        </div>

        <div class="grid grid-cols-3 gap-4 mb-4">
          <div class="text-center">
            <div class="text-sm text-light-dark">请求数</div>
            <div class="text-lg font-medium">{{ service.metrics.requestCount }}</div>
          </div>
          <div class="text-center">
            <div class="text-sm text-light-dark">错误率</div>
            <div class="text-lg font-medium" :class="{
              'text-accent-blue': service.metrics.errorRate < 1,
              'text-accent-yellow': service.metrics.errorRate >= 1 && service.metrics.errorRate < 5,
              'text-accent-orange': service.metrics.errorRate >= 5 && service.metrics.errorRate < 10,
              'text-accent-pink': service.metrics.errorRate >= 10
            }">{{ service.metrics.errorRate }}%</div>
          </div>
          <div class="text-center">
            <div class="text-sm text-light-dark">响应时间</div>
            <div class="text-lg font-medium">{{ service.metrics.avgResponseTime }}ms</div>
          </div>
        </div>

        <div class="text-sm text-light-dark">
          最后活跃: {{ formatTime(service.lastSeen) }}
        </div>
      </div>
    </div>

    <!-- 服务详情弹窗 -->
    <div v-if="selectedService" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">{{ selectedService.name }}</h2>
            <button @click="selectedService = null" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div>
              <h3 class="text-lg font-medium mb-4">基本信息</h3>
              <div class="space-y-2">
                <div class="flex justify-between">
                  <span class="text-light-dark">ID:</span>
                  <span class="font-mono">{{ selectedService.id }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-light-dark">命名空间:</span>
                  <span>{{ selectedService.namespace }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-light-dark">IP:</span>
                  <span>{{ selectedService.ip }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-light-dark">端口:</span>
                  <span>{{ selectedService.port }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-light-dark">状态:</span>
                  <span
                    :class="{
                      'text-accent-blue': selectedService.status === 'active',
                      'text-accent-yellow': selectedService.status === 'inactive',
                      'text-accent-pink': selectedService.status === 'error'
                    }"
                  >
                    {{ selectedService.status === 'active' ? '活跃' : selectedService.status === 'inactive' ? '非活跃' : '错误' }}
                  </span>
                </div>
                <div class="flex justify-between">
                  <span class="text-light-dark">最后活跃:</span>
                  <span>{{ formatTime(selectedService.lastSeen) }}</span>
                </div>
              </div>
            </div>

            <div>
              <h3 class="text-lg font-medium mb-4">性能指标</h3>
              <div class="space-y-2">
                <div class="flex justify-between">
                  <span class="text-light-dark">请求总数:</span>
                  <span>{{ selectedService.metrics.requestCount }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-light-dark">错误率:</span>
                  <span :class="{
                    'text-accent-blue': selectedService.metrics.errorRate < 1,
                    'text-accent-yellow': selectedService.metrics.errorRate >= 1 && selectedService.metrics.errorRate < 5,
                    'text-accent-orange': selectedService.metrics.errorRate >= 5 && selectedService.metrics.errorRate < 10,
                    'text-accent-pink': selectedService.metrics.errorRate >= 10
                  }">{{ selectedService.metrics.errorRate }}%</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-light-dark">平均响应时间:</span>
                  <span>{{ selectedService.metrics.avgResponseTime }}ms</span>
                </div>
              </div>

              <div class="mt-6">
                <div class="h-40" ref="serviceChartRef"></div>
              </div>
            </div>
          </div>

          <div class="mb-6">
            <h3 class="text-lg font-medium mb-4">最近请求</h3>
            <div class="overflow-x-auto">
              <table class="w-full">
                <thead>
                  <tr class="border-b border-dark">
                    <th class="py-2 px-4 text-left">路径</th>
                    <th class="py-2 px-4 text-left">方法</th>
                    <th class="py-2 px-4 text-left">状态码</th>
                    <th class="py-2 px-4 text-left">响应时间</th>
                    <th class="py-2 px-4 text-left">时间</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(trace, index) in serviceTraces" :key="index" class="border-b border-dark">
                    <td class="py-2 px-4 font-mono text-sm">{{ trace.path }}</td>
                    <td class="py-2 px-4">
                      <span :class="{
                        'badge badge-blue': trace.method === 'GET',
                        'badge badge-green': trace.method === 'POST',
                        'badge badge-purple': trace.method === 'PUT',
                        'badge badge-orange': trace.method === 'DELETE',
                        'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(trace.method)
                      }">{{ trace.method }}</span>
                    </td>
                    <td class="py-2 px-4">
                      <span :class="{
                        'text-accent-blue': trace.statusCode < 300,
                        'text-accent-yellow': trace.statusCode >= 300 && trace.statusCode < 400,
                        'text-accent-orange': trace.statusCode >= 400 && trace.statusCode < 500,
                        'text-accent-pink': trace.statusCode >= 500
                      }">{{ trace.statusCode }}</span>
                    </td>
                    <td class="py-2 px-4">{{ trace.duration.toFixed(2) }} ms</td>
                    <td class="py-2 px-4 text-light-dark">{{ formatTime(trace.timestamp) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <div class="flex justify-between">
            <button class="btn btn-outline" @click="selectedService = null">关闭</button>
            <router-link :to="`/faults?service=${selectedService.id}`" class="btn btn-primary">
              创建故障注入
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useServicesStore } from '../stores/services';

// 引入状态管理
const servicesStore = useServicesStore();

// 搜索和过滤
const searchQuery = ref('');
const statusFilter = ref('all');

// 选中的服务
const selectedService = ref<any>(null);
const serviceChartRef = ref(null);

// 模拟服务数据
const services = ref([
  {
    id: '1',
    name: 'user-service',
    namespace: 'default',
    ip: '10.0.0.1',
    port: 8080,
    status: 'active',
    lastSeen: new Date().toISOString(),
    metrics: {
      requestCount: 12543,
      errorRate: 0.5,
      avgResponseTime: 45.2
    }
  },
  {
    id: '2',
    name: 'order-service',
    namespace: 'default',
    ip: '10.0.0.2',
    port: 8081,
    status: 'active',
    lastSeen: new Date().toISOString(),
    metrics: {
      requestCount: 8765,
      errorRate: 1.2,
      avgResponseTime: 78.5
    }
  },
  {
    id: '3',
    name: 'payment-service',
    namespace: 'finance',
    ip: '10.0.0.3',
    port: 8082,
    status: 'inactive',
    lastSeen: new Date(Date.now() - 86400000).toISOString(),
    metrics: {
      requestCount: 4321,
      errorRate: 0.8,
      avgResponseTime: 32.1
    }
  },
  {
    id: '4',
    name: 'inventory-service',
    namespace: 'warehouse',
    ip: '10.0.0.4',
    port: 8083,
    status: 'error',
    lastSeen: new Date(Date.now() - 3600000).toISOString(),
    metrics: {
      requestCount: 2198,
      errorRate: 15.3,
      avgResponseTime: 156.3
    }
  },
  {
    id: '5',
    name: 'notification-service',
    namespace: 'communication',
    ip: '10.0.0.5',
    port: 8084,
    status: 'active',
    lastSeen: new Date().toISOString(),
    metrics: {
      requestCount: 9876,
      errorRate: 0.3,
      avgResponseTime: 28.7
    }
  },
  {
    id: '6',
    name: 'auth-service',
    namespace: 'security',
    ip: '10.0.0.6',
    port: 8085,
    status: 'active',
    lastSeen: new Date().toISOString(),
    metrics: {
      requestCount: 15432,
      errorRate: 0.7,
      avgResponseTime: 52.4
    }
  }
]);

// 模拟服务的请求数据
const serviceTraces = ref([
  {
    path: '/api/users/123',
    method: 'GET',
    statusCode: 200,
    duration: 45.2,
    timestamp: new Date(Date.now() - 120000).toISOString()
  },
  {
    path: '/api/users',
    method: 'POST',
    statusCode: 201,
    duration: 78.5,
    timestamp: new Date(Date.now() - 180000).toISOString()
  },
  {
    path: '/api/users/456',
    method: 'PUT',
    statusCode: 204,
    duration: 32.1,
    timestamp: new Date(Date.now() - 240000).toISOString()
  },
  {
    path: '/api/users/789',
    method: 'DELETE',
    statusCode: 404,
    duration: 12.8,
    timestamp: new Date(Date.now() - 300000).toISOString()
  },
  {
    path: '/api/users/status',
    method: 'GET',
    statusCode: 500,
    duration: 156.3,
    timestamp: new Date(Date.now() - 360000).toISOString()
  }
]);

// 过滤服务
const filteredServices = computed(() => {
  let result = services.value;

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(service =>
      service.name.toLowerCase().includes(query) ||
      service.namespace.toLowerCase().includes(query) ||
      service.ip.includes(query)
    );
  }

  // 状态过滤
  if (statusFilter.value !== 'all') {
    result = result.filter(service => service.status === statusFilter.value);
  }

  return result;
});

// 格式化时间
const formatTime = (timestamp: string) => {
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 选择服务
const selectService = (service: any) => {
  selectedService.value = service;
};

// 获取服务数据
const fetchServices = async () => {
  try {
    await servicesStore.fetchServices();
    // 这里可以用实际数据替换模拟数据
    // services.value = servicesStore.services;
  } catch (error) {
    console.error('获取服务列表失败:', error);
  }
};

// 生命周期钩子
onMounted(() => {
  fetchServices();

  // 设置定时刷新
  const refreshInterval = setInterval(fetchServices, 30000);

  // 清理定时器
  const cleanup = () => {
    clearInterval(refreshInterval);
  };

  // 组件卸载时清理
  return cleanup;
});

// 监听选中服务的变化
watch(selectedService, (_newVal) => {
  // 处理选中服务的变化
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
